/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package crawler.model;

import business.service.MongoDbFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.WriteConcern;
import crawler.common.StaticData;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;

/**
 *
 * @author loctran912
 */
public class StaticModel {

    private static final String STATIC_COLLECTION = "static";
    private static final Logger logger = Logger.getLogger(StaticModel.class);
    private static final Lock createLock_ = new ReentrantLock();
    private static StaticModel _instance = null;

    public static StaticModel getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new StaticModel();

                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    public StaticModel() {
        try {
        } catch (Exception ex) {
            logger.error("StaticModel: " + ex);
        }
    }

    public List<StaticData> getList(int start, int limit) {
        List<StaticData> lstStatic = new LinkedList<>();
        try {
            BasicDBObject basicDBObject = new BasicDBObject("created", -1);
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(STATIC_COLLECTION);
            DBCursor cursor = coll.find().sort(basicDBObject);

            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }

            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                lstStatic.add(fromDB(dbObject));
            }
        } catch (Exception ex) {
            logger.error("PostModel.getPost: " + ex.getMessage(), ex);
        }
        return lstStatic;
    }

    public StaticData getStaticById(String id) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", new ObjectId(id));
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(STATIC_COLLECTION);
            DBCursor cursor = coll.find(basicDBObject);
            if (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                StaticData staticData = fromDB(dbObject);
                return staticData;
            }
        } catch (Exception ex) {
            logger.error("StaticModel.getStaticById: " + ex.getMessage(), ex);
        }
        return null;
    }
    public StaticData getStaticByRemote(String remote) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject("remote", remote);
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(STATIC_COLLECTION);
            DBCursor cursor = coll.find(basicDBObject);
            if (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                StaticData postData = fromDB(dbObject);
                return postData;
            }
        } catch (Exception ex) {
            logger.error("StaticModel.getStaticByRemote: " + ex.getMessage(), ex);
        }
        return null;
    }
    public static StaticData fromDB(DBObject dbObject){
        String objectId = ((ObjectId) dbObject.get("_id")).toString();
        String remote = (String) dbObject.get("remote");
        String local = (String) dbObject.get("local");
        long created = (long) dbObject.get("created");
        StaticData postData = new 
        StaticData(objectId, remote, local, created);
        return postData;
    }
    public long getStaticCount(String pid) {
        long count = 0;
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(STATIC_COLLECTION);
            count = coll.getCount();
        } catch (Exception ex) {
            logger.error("StaticModel.getStaticCount: " + ex.getMessage(), ex);
        }
        return count;
    }

    public boolean remove(String id) {
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(STATIC_COLLECTION);
            coll.remove(new BasicDBObject("_id", new ObjectId(id)));

            return true;
        } catch (Exception ex) {
            logger.error("StaticModel.updateStatic: " + ex.getMessage(), ex);
        }
        return false;
    }
    
    public String addStatic(StaticData postData) {
        String id = "";
        try {
            BasicDBObject basicDBObject = new BasicDBObject()
                    .append("remote", postData.getRemote())
                    .append("local", postData.getLocal())
                    .append("created", postData.getCreated());
            
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(STATIC_COLLECTION);
            coll.insert(basicDBObject, WriteConcern.ACKNOWLEDGED);
            
            ObjectId objectId = (ObjectId)basicDBObject.get( "_id" );
            id = objectId.toString();
        } catch (Exception ex) {
            logger.error("StaticModel.addStatic: " + ex.getMessage(), ex);
        }
        return id;
    }
    
    public boolean updateStatic(StaticData postData) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject()
                    .append("remote", postData.getRemote())
                    .append("local", postData.getLocal())
                    .append("created", postData.getCreated());

            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(STATIC_COLLECTION);
            
            BasicDBObject updateDBObject = new BasicDBObject("$set", basicDBObject);
            BasicDBObject searchDBQuery = new BasicDBObject("_id", new ObjectId(postData.getId()));
            coll.update(searchDBQuery, updateDBObject);
            return true;
        } catch (Exception ex) {
            logger.error("StaticModel.updateStatic: " + ex.getMessage());
        }
        return false;
    }
}
